package controller;

import bean.Dept;
import bean.Employee;
import bean.Message;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.EmployeeService;

import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService service;

    @RequestMapping(value = "/emps", method = RequestMethod.GET)
    public ModelAndView getEmployee(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {

//        使用pageHelper分页插件，进行分页查询
//        pageSize：每页的大小
        PageHelper.startPage(pageNumber, 5);

        List<Employee> employeeList = service.getAllEmployees();

//        pageInfo包含了很多分页查询的信息：页面大小、是否有前一页、、、
//        navigatePage：连续显示的页数
        PageInfo pageInfo = new PageInfo<>(employeeList, 5);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("pageInfo", pageInfo);
        modelAndView.setViewName("returnModelAndViewMethod");

        return modelAndView;
    }

    /* 将数据转为json格式字符串，注意需要导入jackson包 */
    @ResponseBody
    @RequestMapping(value = "/getData", method = RequestMethod.GET)
    /* 返回操作的结果 */
    public Message returnJsonEmployeeData(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {

        PageHelper.startPage(pageNumber, 8);

        List<Employee> employeeList = service.getAllEmployees();

        PageInfo pageInfo = new PageInfo<>(employeeList, 5);

        return Message.success().addData("pageInfo", pageInfo);
    }

    @RequestMapping("/show")
    public String getPage() {
        return "returnJsonMethod";
    }


    @ResponseBody
    @RequestMapping(value = "/addEmp", method = RequestMethod.POST)
    public Message addEmployee(Employee employee) {
        int res = service.addEmploy(employee);
        return Message.success().addData("result", res);
    }
}